package com.Linngdu664.drglaserpointer.client.render;

import com.mojang.blaze3d.vertex.PoseStack;
import com.mojang.math.Quaternion;
import com.mojang.math.Vector3f;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.Font;
import net.minecraft.client.renderer.MultiBufferSource;
import net.minecraft.network.chat.TextComponent;
import net.minecraft.util.Mth;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.phys.Vec3;
import net.minecraftforge.client.event.RenderLevelStageEvent;

public class TextRenderer {
    // todo: third-person view bugs
    public static void renderText(RenderLevelStageEvent event, TextComponent text, Vec3 pos) {
        Minecraft instance = Minecraft.getInstance();
        Player player = instance.player;
        Vec3 playerPos = player.getEyePosition(event.getPartialTick());
        PoseStack matrixStack = event.getPoseStack();
        matrixStack.pushPose();
        Vec3 cameraPosition = instance.gameRenderer.getMainCamera().getPosition();
        Vec3 vec3 = pos.subtract(playerPos);
//        double cx = vec3.x / vec3.length();
//        double cy = vec3.y / vec3.length();
//        double cz = vec3.z / vec3.length();
//        Vector3f vector3f = new Vector3f((float) (Mth.HALF_PI - Mth.atan2(cx, Math.sqrt(1 - cx * cx))), (float) (Mth.HALF_PI - Mth.atan2(cy, Math.sqrt(1 - cy * cy))), (float) (Mth.HALF_PI - Mth.atan2(cx, Math.sqrt(1 - cz * cz))));
        Quaternion rotation = instance.gameRenderer.getMainCamera().rotation();
//        Quaternion rotation = Quaternion.fromXYZ(new Vector3f(Mth.HALF_PI, 0f, 0f));
        matrixStack.translate(pos.x - cameraPosition.x, pos.y - cameraPosition.y, pos.z - cameraPosition.z);
        matrixStack.scale(-0.025F, -0.025F, -0.025F);
        matrixStack.mulPose(rotation);
        Font font = instance.font;
        float f2 = (float)(-font.width(text) / 2);
        MultiBufferSource.BufferSource bufferSource = instance.renderBuffers().bufferSource();
        int packedLight = instance.getEntityRenderDispatcher().getPackedLightCoords(player, event.getPartialTick());
        font.drawInBatch(text, f2, 0f, 0xffffffff, false, matrixStack.last().pose(), bufferSource, true, 0, packedLight);
        matrixStack.popPose();
    }
}
